package com.mysql.opt;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


import reflect.engine.DataBaseStructInfoer;
import system.mysql.schema.base.models.Proc;
import system.mysql.schema.information.models.TRIGGERS;

import common.BlobTypeStringReader;

public class ProcedureOperator extends Operator{
	
	private List<Proc> procList = null;
	
	public ProcedureOperator(){
		this.oprType = "Procedures & Functions";
		this.refresh();
	}
	
	@Override
	public boolean drop(int index) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean dropAll() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public List<String[]> getBackupSQLs() {
		// TODO Auto-generated method stub
		List<String[]> SQLs4b = new ArrayList<String[]>();
		for(int i=0;i<this.procList.size();i++){
			try{
				Proc proc = this.procList.get(i);				
				String[] back = {"Procedure & Function: "+proc.getName(), this.genCreateStatement(proc)};
				SQLs4b.add(back);
			}catch(Exception e){
				e.printStackTrace();
			}			
		}
		return SQLs4b;
	}

	@Override
	public List<String> getNames() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List getObjs() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void refresh() {
		// TODO Auto-generated method stub
		DataBaseStructInfoer dbti = new DataBaseStructInfoer();
		this.procList = dbti.getProcedures();
	}

	private String genCreateStatement(Proc procedure) throws IOException{
		String stat = "/*"+procedure.getType()+" : `"+procedure.getDb() + "`.`" + procedure.getName()+"` */ " + Operator.nextline;
		stat += this.genDropStatement(procedure) + ";" + Operator.nextline;
		stat += "CREATE " + procedure.getType() + " `" + procedure.getName() + "` (" + BlobTypeStringReader.readToString(procedure.getParam_list()) + ")"+ Operator.nextline;;
		if(procedure.getType().equalsIgnoreCase("FUNCTION")){
			String rtn = BlobTypeStringReader.readToString(procedure.getReturns());
			if(!rtn.equalsIgnoreCase("")){
				stat += "RETURNS (" + rtn + ")" + Operator.nextline;
			}
		}		
		stat += this.getComment(procedure);
		stat += BlobTypeStringReader.readToString(procedure.getBody()) + ";";
		return stat;
	}
	
	private String getComment(Proc procedure){
		String str = procedure.getComment();		
		if(!str.equalsIgnoreCase("")){
			str = "COMMENT '" + str + "'" + Operator.nextline;
		}
		return str;
	}
	
	private String genDropStatement(Proc procedure){
		return "DROP "+procedure.getType()+" IF EXISTS `"+procedure.getName()+"`";
	}
	
}
